<?php
/**
 * Description of ClienteDAO
 *
 * @author Magno
 */
class ClienteDAO extends UsuarioDAO{

    protected $conexao;

    protected $mediaDAO;
    protected $statusDAO;
    private $pessoaDAO;
    private $informacaoDAO;
    private $depoimentoDAO;
    private $compraDAO;
    private $conviteDAO;
    private $clienteBonusDAO;
    private $interesseDAO;
    private $votoDAO;
    private $lanceDAO;

    private $join = " SELECT * FROM cliente a INNER JOIN usuario u ON a.usuarioID = u.usuarioID ";

    public function __construct() {
        parent::__construct();
        $this->conexao = Conexao::getConexao();
        $this->pessoaDAO = new PessoaDAO();       
    }

    public function salvar($cliente) {

        try {

            $cliente->setUsuario(parent::salvar($cliente->getUsuario())); 
            
            if($this->existe($cliente->getUsuarioID())) {
                $statment = $this->conexao->prepare("UPDATE cliente SET
                        numLances = :numLances,
                        avisosPorEmail = :avisosPorEmail
                        WHERE usuarioID = :usuarioID");
            }else {

                $statment = $this->conexao->prepare("INSERT INTO cliente(usuarioID,numLances,avisosPorEmail) VALUES (:usuarioID,:numLances,:avisosPorEmail);");
                
            }
            
            if($statment->execute($cliente->toBD())) {
                    
                 $cliente->getPessoa()->setCliente($cliente);
                 $cliente->setPessoa($this->pessoaDAO->salvar($cliente->getPessoa()));

                return $cliente;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ClienteDAO: ".$erros[2]);
            }
                
        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }

    }

    public function excluir($usuarioID) {

        try {
            parent::excluir($usuarioID);
        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }

    }

    public function listar($pagina = 0, $email = "", $login = "", $statusID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = parent::getWhere($email, $login, $statusID);
            $clientes = array();

            $statment = $this->conexao->query( $this->join.$where. " $limite " );

            foreach ( $statment->fetchAll(PDO::FETCH_SERIALIZE) as $row ) {

                $usuarioID = $row['usuarioID'];

                $cliente = new ClienteBean($usuarioID, $row['login'], $row['senha'], $row['email'], $row['ip'], Util::dateToString($row['dataCriacao'])
                        ,null,null,$row['numLances'], $row['avisosPorEmail']);
                $cliente->setStatus($this->statusDAO->buscarPorID($row['statusID']));
                $cliente->setMedia($this->mediaDAO->buscarPorID($row['mediaID']));
                $cliente->setPessoa($this->pessoaDAO->buscarPorID($usuarioID, true));

                if($carregarDependencias){
                    
                    $this->instanciaDependencias();
                    
                    $cliente->setInformacoes($this->informacaoDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setDepoimentos($this->depoimentoDAO->listar(0, $usuarioID, 0, false));
                    $cliente->setCompras($this->compraDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setVotos($this->votoDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setClienteBonus($this->clienteBonusDAO->listar(0, 0, $usuarioID, "", false));
                    $cliente->setInteresses($this->interesseDAO->listarCategoriaProdutoPorCliente(0, $usuarioID));
                    $cliente->setConvites($this->conviteDAO->listar(0, "", $usuarioID, 0, false));
                    $cliente->setLances($this->lanceDAO->listar(0, 0, $usuarioID, false));
                    
                }
                $clientes[] = $cliente;
            }

            return $clientes;

        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }
    }

    public function buscarPorID($usuarioID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query( $this->join." WHERE a.usuarioID = $usuarioID ")->fetch(PDO::FETCH_SERIALIZE);

            if(isset($row['usuarioID']) && $row['usuarioID'] > 0) {
                $usuarioID = $row['usuarioID'];

                $cliente = new ClienteBean($usuarioID, $row['login'], $row['senha'], $row['email'], $row['ip'], Util::dateToString($row['dataCriacao'])
                        ,null,null,$row['numLances'], $row['avisosPorEmail']);
                
                $cliente->setStatus($this->statusDAO->buscarPorID($row['statusID']));
                $cliente->setMedia($this->mediaDAO->buscarPorID($row['mediaID']));
                $cliente->setPessoa($this->pessoaDAO->buscarPorID($usuarioID, true));

                if($carregarDependencias){
                    
                    $this->instanciaDependencias();
                    
                    $cliente->setInformacoes($this->informacaoDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setDepoimentos($this->depoimentoDAO->listar(0, $usuarioID, 0, false));
                    $cliente->setCompras($this->compraDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setVotos($this->votoDAO->listar(0, 0, $usuarioID, 0, false));
                    $cliente->setClienteBonus($this->clienteBonusDAO->listar(0, 0, $usuarioID, "", false));
                    $cliente->setInteresses($this->interesseDAO->listarCategoriaProdutoPorCliente(0, $usuarioID));
                    $cliente->setConvites($this->conviteDAO->listar(0, "", $usuarioID, 0, false));
                    $cliente->setLances($this->lanceDAO->listar(0, 0, $usuarioID, false));

                }
                return $cliente;
            }else {
                return null;
            }


        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }
    }

    public function existe($usuarioID){
        try {

            $row = $this->conexao->query( $this->join." WHERE a.usuarioID = $usuarioID ")->fetch(PDO::FETCH_SERIALIZE);

            if(isset($row['usuarioID']) && $row['usuarioID'] > 0) {
                return true;
            }else {
                return false;
            }

        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }
    }
    
    private function instanciaDependencias(){
        $this->informacaoDAO = new InformacaoDAO();
        $this->depoimentoDAO = new DepoimentoDAO();
        $this->compraDAO = new CompraDAO();
        $this->conviteDAO = new ConviteDAO();
        $this->clienteBonusDAO = new ClienteBonusDAO();
        $this->interesseDAO = new InteresseDAO();
        $this->votoDAO = new VotoDAO();
        $this->lanceDAO = new LanceDAO();
    }

    public function total($email = "", $login = "", $statusID = -1) {
        try {

            $where = parent::getWhere($email, $login, $statusID);
            $total = $this->conexao->query(" SELECT COUNT(a.usuarioID) FROM cliente a INNER JOIN usuario u ON a.usuarioID = u.usuarioID " .$where)->fetch(PDO::FETCH_COLUMN);
            return $total;

        }catch(PDOException $err) {
            throw new Exception("Erro ClienteDAO:".$err->getMessage());
        }
    }
}
?>
